/*
 * Copyright 2011 Rolf Aden
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package com.ec;

import java.io.IOException;
import java.util.Calendar;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.ShortBlob;
import com.google.appengine.api.datastore.Text;

/**
 * Used to convert a given string to a value according to the given type
 * 
 * @author Rolf Aden
 */
class TypeConverter {
	//	TODO change the exception type to something the appengine-mapreduce library
	//	understands as fatal error.
	//	TODO check that the given string value can be converted to the given type,
	//	e.g. for the type "Text string, short" the given string value should not be 
	//	longer than 500 chars. 
	public static Object parse(String type, String value) throws IOException {
		
		if (value == null || value.trim().length() == 0) {
			return null;
		}

		if ("Text string, short".equals(type)) {
			return value;
		} else if ("Text string, long".equals(type)) {
			return new Text(value);
		} else if ("floating point number".equals(type)) {
			return new Double(value);
		} else if ("integer".equals(type)) {
			return new Long(value);			
		} else if ("Boolean".equals(type)) {
			return new Boolean(value);
		} else if ("Byte string, short".equals(type)) {
			// TODO allow a defaultValue too
			return new ShortBlob(new byte[0]);
		} else if ("Byte string, long".equals(type)) {
			// TODO allow a defaultValue too
			return new Blob(new byte[0]);
		} else if ("Date and time".equals(type)) {
			// we get the value here as millis since January 1, 1970, 00:00:00 UTC
			Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(Long.valueOf(value));
			return cal.getTime();
		} else {
			throw new IOException(type + " is unknown");
		}
	}
}
